{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "216E63EBD0DC4C26828C96B784C49B24",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "# GRU"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {
    "id": "35A5BB52AD23476AB3234E38360D557E",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "RNN存在的问题：梯度较容易出现衰减或爆炸（BPTT）  \n",
    "⻔控循环神经⽹络：捕捉时间序列中时间步距离较⼤的依赖关系  \n",
    "**RNN**:  \n",
    "\n",
    "\n",
    "![Image Name](https://cdn.kesci.com/upload/image/q5jjvcykud.png?imageView2/0/w/320/h/320)\n",
    "\n",
    "\n",
    "$$\n",
    "H_{t} = ϕ(X_{t}W_{xh} + H_{t-1}W_{hh} + b_{h})\n",
    "$$\n",
    "**GRU**:\n",
    "\n",
    "\n",
    "![Image Name](https://cdn.kesci.com/upload/image/q5jk0q9suq.png?imageView2/0/w/640/h/640)\n",
    "\n",
    "\n",
    "\n",
    "$$\n",
    "R_{t} = σ(X_tW_{xr} + H_{t−1}W_{hr} + b_r)\\\\    \n",
    "Z_{t} = σ(X_tW_{xz} + H_{t−1}W_{hz} + b_z)\\\\  \n",
    "\\widetilde{H}_t = tanh(X_tW_{xh} + (R_t ⊙H_{t−1})W_{hh} + b_h)\\\\\n",
    "H_t = Z_t⊙H_{t−1} + (1−Z_t)⊙\\widetilde{H}_t\n",
    "$$\n",
    "• 重置⻔有助于捕捉时间序列⾥短期的依赖关系；  \n",
    "• 更新⻔有助于捕捉时间序列⾥⻓期的依赖关系。    \n",
    "### 载入数据集"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "id": "303B4A29B33E4646B59188EC4D57BA14",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['.ipynb_checkpoints',\n",
       " 'd2lzh1981',\n",
       " 'd2l_jay9460',\n",
       " 'FashionMNIST2065',\n",
       " 'houseprices2807',\n",
       " 'jaychou_lyrics4703',\n",
       " 'Task1',\n",
       " 'Task2-RNN',\n",
       " 'Task3',\n",
       " 'Task4',\n",
       " 'Task5-CNN',\n",
       " 'Untitled.ipynb']"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import os\n",
    "os.listdir('..')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "id": "954C3D57745047D587E4BFA23CE0BFA0",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import torch\n",
    "from torch import nn, optim\n",
    "import torch.nn.functional as F"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "id": "64E106307FF64926859FD92A826422D6",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [
    {
     "ename": "ModuleNotFoundError",
     "evalue": "No module named 'torchtext'",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mModuleNotFoundError\u001b[0m                       Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-3-2893812b899e>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[0;32m      1\u001b[0m \u001b[1;32mimport\u001b[0m \u001b[0msys\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      2\u001b[0m \u001b[0msys\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mpath\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mappend\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"..\"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 3\u001b[1;33m \u001b[1;32mimport\u001b[0m \u001b[0md2l_jay9460\u001b[0m \u001b[1;32mas\u001b[0m \u001b[0md2l\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m      4\u001b[0m \u001b[0mdevice\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mtorch\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mdevice\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m'cuda'\u001b[0m \u001b[1;32mif\u001b[0m \u001b[0mtorch\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mcuda\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mis_available\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m \u001b[1;32melse\u001b[0m \u001b[1;34m'cpu'\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      5\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;32mD:\\Anaconda3\\Anaconda3_jupyter_documents\\动手学深度学习PyTorch\\d2l_jay9460\\__init__.py\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[1;32mfrom\u001b[0m \u001b[1;33m.\u001b[0m\u001b[0mutils\u001b[0m \u001b[1;32mimport\u001b[0m \u001b[1;33m*\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m      2\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;32mD:\\Anaconda3\\Anaconda3_jupyter_documents\\动手学深度学习PyTorch\\d2l_jay9460\\utils.py\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[0;32m     19\u001b[0m \u001b[1;32mimport\u001b[0m \u001b[0mtorchvision\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m     20\u001b[0m \u001b[1;32mimport\u001b[0m \u001b[0mtorchvision\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mtransforms\u001b[0m \u001b[1;32mas\u001b[0m \u001b[0mtransforms\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m---> 21\u001b[1;33m \u001b[1;32mimport\u001b[0m \u001b[0mtorchtext\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m     22\u001b[0m \u001b[1;32mimport\u001b[0m \u001b[0mtorchtext\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mvocab\u001b[0m \u001b[1;32mas\u001b[0m \u001b[0mVocab\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m     23\u001b[0m \u001b[1;32mimport\u001b[0m \u001b[0mnumpy\u001b[0m \u001b[1;32mas\u001b[0m \u001b[0mnp\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;31mModuleNotFoundError\u001b[0m: No module named 'torchtext'"
     ]
    }
   ],
   "source": [
    "import sys\n",
    "sys.path.append(\"..\")\n",
    "import d2l_jay9460 as d2l\n",
    "device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n",
    "\n",
    "(corpus_indices, char_to_idx, idx_to_char, vocab_size) = d2l.load_data_jay_lyrics()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "CE7C3A96CFCC449A8D5F65577841999B",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### 初始化参数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "id": "9FB61618A6DB406D843C7BCEDDA63EB1",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "will use cpu\n"
     ]
    }
   ],
   "source": [
    "num_inputs, num_hiddens, num_outputs = vocab_size, 256, vocab_size\n",
    "print('will use', device)\n",
    "\n",
    "def get_params():  \n",
    "    def _one(shape):\n",
    "        ts = torch.tensor(np.random.normal(0, 0.01, size=shape), device=device, dtype=torch.float32) #正态分布\n",
    "        return torch.nn.Parameter(ts, requires_grad=True)\n",
    "    def _three():\n",
    "        return (_one((num_inputs, num_hiddens)),\n",
    "                _one((num_hiddens, num_hiddens)),\n",
    "                torch.nn.Parameter(torch.zeros(num_hiddens, device=device, dtype=torch.float32), requires_grad=True))\n",
    "     \n",
    "    W_xz, W_hz, b_z = _three()  # 更新门参数\n",
    "    W_xr, W_hr, b_r = _three()  # 重置门参数\n",
    "    W_xh, W_hh, b_h = _three()  # 候选隐藏状态参数\n",
    "    \n",
    "    # 输出层参数\n",
    "    W_hq = _one((num_hiddens, num_outputs))\n",
    "    b_q = torch.nn.Parameter(torch.zeros(num_outputs, device=device, dtype=torch.float32), requires_grad=True)\n",
    "    return nn.ParameterList([W_xz, W_hz, b_z, W_xr, W_hr, b_r, W_xh, W_hh, b_h, W_hq, b_q])\n",
    "\n",
    "def init_gru_state(batch_size, num_hiddens, device):   #隐藏状态初始化\n",
    "    return (torch.zeros((batch_size, num_hiddens), device=device), )"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "1CD23FE7F21C4D5D82702BE6CACE3DBF",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### GRU模型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "id": "F4D5CB26DCBE45E58DECB282979C85D0",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "def gru(inputs, state, params):\n",
    "    W_xz, W_hz, b_z, W_xr, W_hr, b_r, W_xh, W_hh, b_h, W_hq, b_q = params\n",
    "    H, = state\n",
    "    outputs = []\n",
    "    for X in inputs:\n",
    "        Z = torch.sigmoid(torch.matmul(X, W_xz) + torch.matmul(H, W_hz) + b_z)\n",
    "        R = torch.sigmoid(torch.matmul(X, W_xr) + torch.matmul(H, W_hr) + b_r)\n",
    "        H_tilda = torch.tanh(torch.matmul(X, W_xh) + R * torch.matmul(H, W_hh) + b_h)\n",
    "        H = Z * H + (1 - Z) * H_tilda\n",
    "        Y = torch.matmul(H, W_hq) + b_q\n",
    "        outputs.append(Y)\n",
    "    return outputs, (H,)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "DC589ABFFE464B32BD3CADCE9C64DE87",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### 训练模型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "id": "CF81DCA87B884C2E996632B5E49BB9D9",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "num_epochs, num_steps, batch_size, lr, clipping_theta = 160, 35, 32, 1e2, 1e-2\n",
    "pred_period, pred_len, prefixes = 40, 50, ['分开', '不分开']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "id": "4FA0FC8D41C04605BD1FCA235D00233B",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 40, perplexity 149.271885, time 1.17 sec\n",
      " - 分开 我想我不不 我想你的让我 你想我的让我 你想我不想 我想你我想想想想想你想你的可爱人  坏我的让我\n",
      " - 不分开 我想你我不想 你不我 我想你的爱爱 我想你的让我 我想你我想想想想想想你的可爱人  坏我的让我 我\n",
      "epoch 160, perplexity 1.427383, time 1.16 sec\n",
      " - 分开 我已带口 你已已是不起 让你知没面对我 甩散球我满腔的怒火 我想揍你已经很久 别想躲 说你眼睛看着\n",
      " - 不分开 整过 是你开的玩笑 想通 却又再考倒我 说散 你想很久了吧? 败给你的黑色幽默 说散 你想很久了吧\n"
     ]
    }
   ],
   "source": [
    "d2l.train_and_predict_rnn(gru, get_params, init_gru_state, num_hiddens,\n",
    "                          vocab_size, device, corpus_indices, idx_to_char,\n",
    "                          char_to_idx, False, num_epochs, num_steps, lr,\n",
    "                          clipping_theta, batch_size, pred_period, pred_len,\n",
    "                          prefixes)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "32035E22A7B04D3A8F787C7CB15F366F",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### 简洁实现"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "id": "CAE438B5EC9A454B8C1AAAF4EFEF7548",
    "jupyter": {},
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 40, perplexity 1.016101, time 0.89 sec\n",
      " - 分开始想像 爸和妈当年的模样 说著一口吴侬软语的姑娘缓缓走过外滩 消失的 旧时光 一九四三 回头看 的片\n",
      " - 不分开暴风圈来不及逃 我不能再想 我不能再想 我不 我不 我不能 爱情走的太快就像龙卷风 不能承受我已无处\n",
      "epoch 80, perplexity 1.010881, time 0.96 sec\n",
      " - 分开都会值得去做 我想大声宣布 对你依依不舍 连隔壁邻居都猜到我现在的感受 河边的风 在吹着头发飘动 牵\n",
      " - 不分开暴风圈来不及逃 我不能再想 我不能再想 我不 我不 我不能 爱情走的太快就像龙卷风 不能承受我已无处\n",
      "epoch 120, perplexity 1.011403, time 0.95 sec\n",
      " - 分开的我爱你看棒球 想这样没担忧 唱着歌 一直走 我想就这样牵着你的手不放开 爱可不可以简简单单没有伤害\n",
      " - 不分开暴风圈来不及逃 我不能再想 我不能再想 我不 我不 我不能 爱情走的太快就像龙卷风 不能承受我已无处\n",
      "epoch 160, perplexity 1.058085, time 0.88 sec\n",
      " - 分开始打呼 管到当初爱你的时空 停格内容不忠 所有回忆对着我进攻   简单爱情来的太快就像龙卷风 离不开\n",
      " - 不分开始打呼 管家是一只是我怕眼泪撑不住 不懂 你给我抬起头 有话去对医药箱说 别怪我 别怪我 说你怎么面\n"
     ]
    }
   ],
   "source": [
    "num_hiddens=256\n",
    "num_epochs, num_steps, batch_size, lr, clipping_theta = 160, 35, 32, 1e2, 1e-2\n",
    "pred_period, pred_len, prefixes = 40, 50, ['分开', '不分开']\n",
    "\n",
    "lr = 1e-2 # 注意调整学习率\n",
    "gru_layer = nn.GRU(input_size=vocab_size, hidden_size=num_hiddens)\n",
    "model = d2l.RNNModel(gru_layer, vocab_size).to(device)\n",
    "d2l.train_and_predict_rnn_pytorch(model, num_hiddens, vocab_size, device,\n",
    "                                corpus_indices, idx_to_char, char_to_idx,\n",
    "                                num_epochs, num_steps, lr, clipping_theta,\n",
    "                                batch_size, pred_period, pred_len, prefixes)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "15C47CF30681418997AEDB9F08C15C9B",
    "jupyter": {},
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "# LSTM"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {
    "id": "E7D0864A57DB432483AD1B0C89171313",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "** 长短期记忆long short-term memory **:  \n",
    "遗忘门:控制上一时间步的记忆细胞 \n",
    "输入门:控制当前时间步的输入  \n",
    "输出门:控制从记忆细胞到隐藏状态  \n",
    "记忆细胞：⼀种特殊的隐藏状态的信息的流动  \n",
    "\n",
    "\n",
    "![Image Name](https://cdn.kesci.com/upload/image/q5jk2bnnej.png?imageView2/0/w/640/h/640)\n",
    "\n",
    "$$\n",
    "I_t = σ(X_tW_{xi} + H_{t−1}W_{hi} + b_i) \\\\\n",
    "F_t = σ(X_tW_{xf} + H_{t−1}W_{hf} + b_f)\\\\\n",
    "O_t = σ(X_tW_{xo} + H_{t−1}W_{ho} + b_o)\\\\\n",
    "\\widetilde{C}_t = tanh(X_tW_{xc} + H_{t−1}W_{hc} + b_c)\\\\\n",
    "C_t = F_t ⊙C_{t−1} + I_t ⊙\\widetilde{C}_t\\\\\n",
    "H_t = O_t⊙tanh(C_t)\n",
    "$$\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "33A4C20200044DFC80CD2FB42F2D8CA0",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### 初始化参数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "id": "E296216AE65A40608DA0B7856091AA39",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "will use cpu\n"
     ]
    }
   ],
   "source": [
    "num_inputs, num_hiddens, num_outputs = vocab_size, 256, vocab_size\n",
    "print('will use', device)\n",
    "\n",
    "def get_params():\n",
    "    def _one(shape):\n",
    "        ts = torch.tensor(np.random.normal(0, 0.01, size=shape), device=device, dtype=torch.float32)\n",
    "        return torch.nn.Parameter(ts, requires_grad=True)\n",
    "    def _three():\n",
    "        return (_one((num_inputs, num_hiddens)),\n",
    "                _one((num_hiddens, num_hiddens)),\n",
    "                torch.nn.Parameter(torch.zeros(num_hiddens, device=device, dtype=torch.float32), requires_grad=True))\n",
    "    \n",
    "    W_xi, W_hi, b_i = _three()  # 输入门参数\n",
    "    W_xf, W_hf, b_f = _three()  # 遗忘门参数\n",
    "    W_xo, W_ho, b_o = _three()  # 输出门参数\n",
    "    W_xc, W_hc, b_c = _three()  # 候选记忆细胞参数\n",
    "    \n",
    "    # 输出层参数\n",
    "    W_hq = _one((num_hiddens, num_outputs))\n",
    "    b_q = torch.nn.Parameter(torch.zeros(num_outputs, device=device, dtype=torch.float32), requires_grad=True)\n",
    "    return nn.ParameterList([W_xi, W_hi, b_i, W_xf, W_hf, b_f, W_xo, W_ho, b_o, W_xc, W_hc, b_c, W_hq, b_q])\n",
    "\n",
    "def init_lstm_state(batch_size, num_hiddens, device):\n",
    "    return (torch.zeros((batch_size, num_hiddens), device=device), \n",
    "            torch.zeros((batch_size, num_hiddens), device=device))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "91D90EADF26C40728E0CBB1849E3FCF3",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### LSTM模型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "id": "27A0EBB56386481F895FA2FFB0E9180F",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [],
   "source": [
    "def lstm(inputs, state, params):\n",
    "    [W_xi, W_hi, b_i, W_xf, W_hf, b_f, W_xo, W_ho, b_o, W_xc, W_hc, b_c, W_hq, b_q] = params\n",
    "    (H, C) = state\n",
    "    outputs = []\n",
    "    for X in inputs:\n",
    "        I = torch.sigmoid(torch.matmul(X, W_xi) + torch.matmul(H, W_hi) + b_i)\n",
    "        F = torch.sigmoid(torch.matmul(X, W_xf) + torch.matmul(H, W_hf) + b_f)\n",
    "        O = torch.sigmoid(torch.matmul(X, W_xo) + torch.matmul(H, W_ho) + b_o)\n",
    "        C_tilda = torch.tanh(torch.matmul(X, W_xc) + torch.matmul(H, W_hc) + b_c)\n",
    "        C = F * C + I * C_tilda\n",
    "        H = O * C.tanh()\n",
    "        Y = torch.matmul(H, W_hq) + b_q\n",
    "        outputs.append(Y)\n",
    "    return outputs, (H, C)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "40C5775290DB48DB937B836471F2AC17",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### 训练模型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "id": "DD60C69E13F84A17BA441F7E75984E2F",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 40, perplexity 211.457328, time 1.51 sec\n",
      " - 分开 我不的我 我不的我 我不不 我不的我 我不不 我不的我 我不不 我不的我 我不不 我不的我 我不不\n",
      " - 不分开 我不不 我不的我 我不不 我不的我 我不不 我不的我 我不不 我不的我 我不不 我不的我 我不不 \n",
      "epoch 80, perplexity 68.458662, time 1.50 sec\n",
      " - 分开 我想你这你 我不要这你 我不要这你 我不要这你 我不要这你 我不要这你 我不要这你 我不要这你 我\n",
      " - 不分开 我想你你的你 我想要你 我不要 我不要 我不要 我不要 我不要 我不要 我不要 我不要 我不要 我\n",
      "epoch 120, perplexity 15.034657, time 1.49 sec\n",
      " - 分开 我想你你的你笑 不知不觉 你你了一我不我 别发抖 快给我抬起起着你 别发抖 快给我抬起头 有你去对\n",
      " - 不分开 我想你你 我不要再想我 不知不觉 你你了离不我 不知不觉 你跟了离不我 不知不觉 我该了这节活 后\n",
      "epoch 160, perplexity 3.897414, time 1.49 sec\n",
      " - 分开 我想带你里嵩山 学少林跟了了刚 我想就你了嵩着 我想去这生嵩 不天到双截棍 哼哼哈兮 快使用双截棍\n",
      " - 不分开 我 我你你的微笑 像通  又又我 我想就这样牵着你的手不放  穿过来回单单 我 想和你样堡堡 我想\n"
     ]
    }
   ],
   "source": [
    "num_epochs, num_steps, batch_size, lr, clipping_theta = 160, 35, 32, 1e2, 1e-2\n",
    "pred_period, pred_len, prefixes = 40, 50, ['分开', '不分开']\n",
    "\n",
    "d2l.train_and_predict_rnn(lstm, get_params, init_lstm_state, num_hiddens,\n",
    "                          vocab_size, device, corpus_indices, idx_to_char,\n",
    "                          char_to_idx, False, num_epochs, num_steps, lr,\n",
    "                          clipping_theta, batch_size, pred_period, pred_len,\n",
    "                          prefixes)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "F6D1F7613F63401CBDD49FBD7E611B4A",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "### 简洁实现"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "id": "8AC2F2314D8C4DA097334B838732F9D2",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 40, perplexity 1.019881, time 1.04 sec\n",
      " - 分开始打呼 管家是一只会说法语举止优雅的猪 吸血前会念约翰福音做为弥补 拥有一双蓝色眼睛的凯萨琳公主 专\n",
      " - 不分开的玩笑 想通 却又再考倒我 说散 你想很久了吧? 败给你的黑色幽默 不想太多 我想一定是我听错弄错搞\n",
      "epoch 80, perplexity 1.013078, time 1.01 sec\n",
      " - 分开的话像语言暴力 我已无能为力再提起 决定中断熟悉 然后在这里 不限日期 然后将过去 慢慢温习 让我爱\n",
      " - 不分开的玩笑 想通 却又再考倒我 说散 你想很久了吧? 败给你的黑色幽默 说散 你想很久了吧? 我的认真败\n",
      "epoch 120, perplexity 1.010264, time 1.01 sec\n",
      " - 分开 我们儿子她人在江南等我 泪不休 语沉默 一壶好酒 再来一碗热粥 配上几斤的牛肉 我说店小二 三两银\n",
      " - 不分开 我有你看棒球 想这样没担忧 唱着歌 一直走 我想就这样牵着你的手不放开 爱可不可以简简单单没有伤害\n",
      "epoch 160, perplexity 1.008950, time 1.02 sec\n",
      " - 分开 我才  原来我只想要你 陪我去吃汉堡  说穿了其实我的愿望就怎么小 就怎么每天祈祷我的心跳你知道 \n",
      " - 不分开 我才你看 我想要再这样打我妈妈 我说的话 你甘会听 不要再这样打我妈妈 难道你手不会痛吗 其实我回\n"
     ]
    }
   ],
   "source": [
    "num_hiddens=256\n",
    "num_epochs, num_steps, batch_size, lr, clipping_theta = 160, 35, 32, 1e2, 1e-2\n",
    "pred_period, pred_len, prefixes = 40, 50, ['分开', '不分开']\n",
    "\n",
    "lr = 1e-2 # 注意调整学习率\n",
    "lstm_layer = nn.LSTM(input_size=vocab_size, hidden_size=num_hiddens)\n",
    "model = d2l.RNNModel(lstm_layer, vocab_size)\n",
    "d2l.train_and_predict_rnn_pytorch(model, num_hiddens, vocab_size, device,\n",
    "                                corpus_indices, idx_to_char, char_to_idx,\n",
    "                                num_epochs, num_steps, lr, clipping_theta,\n",
    "                                batch_size, pred_period, pred_len, prefixes)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {
    "id": "A5D90CA5217B4DB380BEF1CD17338BB6",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "# 深度循环神经网络  \n",
    "\n",
    "![Image Name](https://cdn.kesci.com/upload/image/q5jk3z1hvz.png?imageView2/0/w/320/h/320)\n",
    "\n",
    "\n",
    "$$\n",
    "\\boldsymbol{H}_t^{(1)} = \\phi(\\boldsymbol{X}_t \\boldsymbol{W}_{xh}^{(1)} + \\boldsymbol{H}_{t-1}^{(1)} \\boldsymbol{W}_{hh}^{(1)} + \\boldsymbol{b}_h^{(1)})\\\\\n",
    "\\boldsymbol{H}_t^{(\\ell)} = \\phi(\\boldsymbol{H}_t^{(\\ell-1)} \\boldsymbol{W}_{xh}^{(\\ell)} + \\boldsymbol{H}_{t-1}^{(\\ell)} \\boldsymbol{W}_{hh}^{(\\ell)} + \\boldsymbol{b}_h^{(\\ell)})\\\\\n",
    "\\boldsymbol{O}_t = \\boldsymbol{H}_t^{(L)} \\boldsymbol{W}_{hq} + \\boldsymbol{b}_q\n",
    "$$"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "id": "9E06D2B447EA485B88F31C9B57ED3A79",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 40, perplexity 12.840496, time 1.52 sec\n",
      " - 分开我 想你的话我在想再你的让我女疼 我想你 我有要有 想你你 想你的让我女沉 我想你你 想你的让我女沉\n",
      " - 不分开的经爱女人 坏坏的让我疯狂的可爱女人 坏坏的让我疯狂的可爱女人 坏坏的让我疯狂的可爱女人 坏坏的让我\n",
      "epoch 80, perplexity 1.247634, time 1.52 sec\n",
      " - 分开有一条热昏头的响尾蛇 无力的躺在干枯的河 在等待雨季来临变沼泽 灰狼啃食著水鹿的骨头 秃鹰盘旋死盯着\n",
      " - 不分开的会手 穿梭放受 一朵一朵因你而香 试图让夕阳飞翔 带领你我环绕大自然 迎著风 开始共渡每一天 手牵\n",
      "epoch 120, perplexity 1.021974, time 1.56 sec\n",
      " - 分开我妈妈 我有多重要 我后悔没让你知道 安静的听你撒娇 看你睡著一直到老 就是开不了口让她知道 就是那\n",
      " - 不分开的会堡  想要将我不投 又不会掩护我 选你这种队友 瞎透了我 说你说 分数怎么停留 一直在停留 谁让\n",
      "epoch 160, perplexity 1.016324, time 1.59 sec\n",
      " - 分开在没有一个人身留  旧时光 一九四三 在回忆 的路上 时间变好慢 老街坊 小弄堂 是属于那年代白墙黑\n",
      " - 不分开的我有 有样的要再这样打我妈妈 难道你手不会痛吗 不要再这样打我妈妈 难道你手不会痛吗 不要再这样打\n"
     ]
    }
   ],
   "source": [
    "\n",
    "\n",
    "num_hiddens=256\n",
    "num_epochs, num_steps, batch_size, lr, clipping_theta = 160, 35, 32, 1e2, 1e-2\n",
    "pred_period, pred_len, prefixes = 40, 50, ['分开', '不分开']\n",
    "\n",
    "lr = 1e-2 # 注意调整学习率\n",
    "\n",
    "gru_layer = nn.LSTM(input_size=vocab_size, hidden_size=num_hiddens,num_layers=2)\n",
    "model = d2l.RNNModel(gru_layer, vocab_size).to(device)\n",
    "d2l.train_and_predict_rnn_pytorch(model, num_hiddens, vocab_size, device,\n",
    "                                corpus_indices, idx_to_char, char_to_idx,\n",
    "                                num_epochs, num_steps, lr, clipping_theta,\n",
    "                                batch_size, pred_period, pred_len, prefixes)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "id": "E386044D687F4D5D862CE5F6E3E2C00A",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 40, perplexity 276.815235, time 8.50 sec\n",
      " - 分开                                                  \n",
      " - 不分开                                                  \n",
      "epoch 80, perplexity 276.278550, time 8.51 sec\n",
      " - 分开                                                  \n",
      " - 不分开                                                  \n",
      "epoch 120, perplexity 276.146710, time 8.53 sec\n",
      " - 分开                                                  \n",
      " - 不分开                                                  \n",
      "epoch 160, perplexity 275.739864, time 9.04 sec\n",
      " - 分开                                                  \n",
      " - 不分开                                                  \n"
     ]
    }
   ],
   "source": [
    "gru_layer = nn.LSTM(input_size=vocab_size, hidden_size=num_hiddens,num_layers=6)\n",
    "model = d2l.RNNModel(gru_layer, vocab_size).to(device)\n",
    "d2l.train_and_predict_rnn_pytorch(model, num_hiddens, vocab_size, device,\n",
    "                                corpus_indices, idx_to_char, char_to_idx,\n",
    "                                num_epochs, num_steps, lr, clipping_theta,\n",
    "                                batch_size, pred_period, pred_len, prefixes)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {
    "id": "6F10BD29920D44F1808692B1AAED1FA7",
    "jupyter": {},
    "mdEditEnable": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "source": [
    "# 双向循环神经网络 \n",
    "\n",
    "![Image Name](https://cdn.kesci.com/upload/image/q5j8hmgyrz.png?imageView2/0/w/320/h/320)\n",
    "\n",
    "$$ \n",
    "\\begin{aligned} \\overrightarrow{\\boldsymbol{H}}_t &= \\phi(\\boldsymbol{X}_t \\boldsymbol{W}_{xh}^{(f)} + \\overrightarrow{\\boldsymbol{H}}_{t-1} \\boldsymbol{W}_{hh}^{(f)} + \\boldsymbol{b}_h^{(f)})\\\\\n",
    "\\overleftarrow{\\boldsymbol{H}}_t &= \\phi(\\boldsymbol{X}_t \\boldsymbol{W}_{xh}^{(b)} + \\overleftarrow{\\boldsymbol{H}}_{t+1} \\boldsymbol{W}_{hh}^{(b)} + \\boldsymbol{b}_h^{(b)}) \\end{aligned} $$\n",
    "$$\n",
    "\\boldsymbol{H}_t=(\\overrightarrow{\\boldsymbol{H}}_{t}, \\overleftarrow{\\boldsymbol{H}}_t)\n",
    "$$\n",
    "$$\n",
    "\\boldsymbol{O}_t = \\boldsymbol{H}_t \\boldsymbol{W}_{hq} + \\boldsymbol{b}_q\n",
    "$$"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {
    "id": "176C228203A040D38D18DC194099C9EA",
    "jupyter": {},
    "scrolled": false,
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 40, perplexity 1.001741, time 0.91 sec\n",
      " - 分开始开始开始开始开始开始开始开始开始开始开始开始开始开始开始开始开始开始开始开始开始开始开始开始开始开\n",
      " - 不分开始开始开始开始开始开始开始开始开始开始开始开始开始开始开始开始开始开始开始开始开始开始开始开始开始开\n",
      "epoch 80, perplexity 1.000520, time 0.91 sec\n",
      " - 分开始开始开始开始开始开始开始开始开始开始开始开始开始开始开始开始开始开始开始开始开始开始开始开始开始开\n",
      " - 不分开始开始开始开始开始开始开始开始开始开始开始开始开始开始开始开始开始开始开始开始开始开始开始开始开始开\n",
      "epoch 120, perplexity 1.000255, time 0.99 sec\n",
      " - 分开始开始开始开始开始开始开始开始开始开始开始开始开始开始开始开始开始开始开始开始开始开始开始开始开始开\n",
      " - 不分开球我球我球我球我球我球我球我球我球我球我球我球我球我球我球我球我球我球我球我球我球我球我球我球我球我\n",
      "epoch 160, perplexity 1.000151, time 0.92 sec\n",
      " - 分开始开始开始开始开始开始开始开始开始开始开始开始开始开始开始开始开始开始开始开始开始开始开始开始开始开\n",
      " - 不分开球我球我球我球我球我球我球我球我球我球我球我球我球我球我球我球我球我球我球我球我球我球我球我球我球我\n"
     ]
    }
   ],
   "source": [
    "num_hiddens=128\n",
    "num_epochs, num_steps, batch_size, lr, clipping_theta = 160, 35, 32, 1e-2, 1e-2\n",
    "pred_period, pred_len, prefixes = 40, 50, ['分开', '不分开']\n",
    "\n",
    "lr = 1e-2 # 注意调整学习率\n",
    "\n",
    "gru_layer = nn.GRU(input_size=vocab_size, hidden_size=num_hiddens,bidirectional=True)\n",
    "model = d2l.RNNModel(gru_layer, vocab_size).to(device)\n",
    "d2l.train_and_predict_rnn_pytorch(model, num_hiddens, vocab_size, device,\n",
    "                                corpus_indices, idx_to_char, char_to_idx,\n",
    "                                num_epochs, num_steps, lr, clipping_theta,\n",
    "                                batch_size, pred_period, pred_len, prefixes)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "412543B3642948FA89C831603F7362BA",
    "jupyter": {},
    "slideshow": {
     "slide_type": "slide"
    },
    "tags": []
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
